package com.effectiv.gooruda.rest.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.stereotype.Component;

import com.effectiv.gooruda.rest.ext.ExtResponse;
import com.effectiv.gooruda.rest.ext.SecurityContextHolder;
import com.effectiv.gooruda.rest.service.api.DataStorageService;

import com.mongodb.DBObject;
import com.mongodb.util.JSON;

@Slf4j
@Component
public class DataStorageServiceImpl extends DataStorageService{
	
	@Autowired
	private MongoTemplate template;
	
	private String COLLECTION_NAME_TEMPLATE = "c_app_coll_";
	
	@Override
	public Response save(String collection, String data) {
		
		log.info("Application - {}", SecurityContextHolder.get());
		
		DBObject dbObject = (DBObject) JSON.parse(data);
		//dbObject.put("_id", null);
		
		String collName = COLLECTION_NAME_TEMPLATE + collection + "_" + "";
		
		template.getCollection(collName).insert(dbObject);
		
		
		ExtResponse res = new ExtResponse();
		//res.setId(u.getId());
		res.setValue(JSON.serialize(dbObject));
		res.setMessage("Document added successfully.");
		
		GenericEntity<ExtResponse> entity = new GenericEntity<ExtResponse>(res, ExtResponse.class);
		
		ResponseBuilder builder = Response.ok(entity);
		
		return builder.build();
		
		
	}

	@Override
	public Response findAll(String collection, String query) {
		
		log.debug("Query = {}", query);
		
		BasicQuery q = new BasicQuery(query);
		
		String collectionName = COLLECTION_NAME_TEMPLATE + collection + "_" + "";
		
		List data = template.find(q, Map.class, collectionName);
		List<String> dataList = null;
		if(data != null){
			
			dataList = new ArrayList<String>();
			
			for(Object o : data){
				
				log.info("Object = {}", o);
				
				dataList.add(JSON.serialize(data));
			}
		}
		
		ExtResponse res = new ExtResponse();
		
		res.setValue(dataList);
		
		GenericEntity<ExtResponse> entity = new GenericEntity<ExtResponse>(res, ExtResponse.class);
		
		ResponseBuilder builder = Response.ok(entity);
		
		return builder.build();
		
		
		
	}
	
}
